package com.siblings.loan.ui.loan.impl

import android.content.Context
import com.siblings.loan.http.ApiService
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.IHttpCallback
import com.siblings.loan.status.StatusRepository
import com.siblings.loan.ui.loan.view.ISibLoanApplyView
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.mvp.presenter.MvpPresenter
import org.json.JSONObject

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/15 13:45
 * @Annotation：贷款申请 Presenter 实现
 */
class SibLoanApplyPresenterImpl(context: Context?) : MvpPresenter<ISibLoanApplyView>(context) {

    private var applyModel: SibLoanApplyModelImpl? = null
    init {
        applyModel = SibLoanApplyModelImpl()
    }

    /**
     * 获取贷款信息
     */
    fun loadSibApplyDataAction(){
        val params = JSONObject().addCommonParams()
        params.put("path", ApiService.API_PATH.SIB_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("amount",mvpView.getSibApplyAmount())
        val applyDays = mvpView.getSibApplyDays()
        if (applyDays.isNotEmpty()){
            params.put("days",applyDays)
        }
        applyModel!!.loadSibApplyDataAction(params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            //是否允许修改申请金额，不允许修改则不显示Seekbar
                            val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                            when(chooseAmountFlag){
                                true -> {//允许选择贷款额度
                                    mvpView.showSibOptionalViews(obj)
                                }
                                else -> {//不允许选择贷款额度
                                    mvpView.showSibNotOptionalViews()
                                }
                            }

                            //设置贷款期限
                            mvpView.showSibLoanDurationList(obj)
                            //设置明细
                            mvpView.showSibLoadDetailsList(obj)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 检查总流程，是否存在指定类型的订单
     */
    fun onSibCheckProcessAction(){
        val data = JSONObject(SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_PROCESS))
        //1、判断是否存在 订单状态
        if (data.has("orderStatus")){
            val orderStatus = data.optString("orderStatus")
            //待还款 || 放款中 || 申请贷款被拒绝
            if (StatusRepository(null,orderStatus).isRepayNow()
                || StatusRepository(null,orderStatus).isDisbursing()
                || StatusRepository(null,orderStatus).isRejected()){
                mvpView.showSibLoanApplyFailed()
                return
            }
        }

        //2、判断是否存在 贷款申请状态
        if (data.has("applyStatus")){
            val applyStatus = data.optString("applyStatus")
            //审核中 || 被拒绝
            if (StatusRepository(applyStatus).isReviewing() || StatusRepository(applyStatus).isRejected()){
                mvpView.showSibLoanApplyFailed()
                return
            }
        }

        //3、创建贷款订单
//        onSibCreateApplyOrderAction()
    }

    /**
     * 创建贷款申请订单
     */
    fun onSibCreateApplyOrderAction(){
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SIB_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("amount",mvpView.getSibApplyAmount())
            put("days",mvpView.getSibApplyDays())
        }
        applyModel!!.onSibCreateApplyOrderAction(params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView.hideSibLoading()
                val msg = data.optString("msg")
                mvpView!!.showSibToast(msg)
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView.showSibLoanApplySuccess()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 是否是新用户
     */
//    private fun isNewUser(): Boolean{
//        val obj = JSONObject(SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_PROCESS))
//        if (!obj.has("userType")){
//            return true
//        }
//        return obj.optString("userType") == "NEW"
//    }
}